package com.huonan.component.es.refactoring;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huonan.component.es.ESConfig;
import com.huonan.component.es.entity.EsHits;

/**
 * 具体处理和es交互
 */
public class EsHandler {

    public static EsHits search(ESConfig env, String scrollId) {
        if (StrUtil.isNotEmpty(scrollId)) {
            JSONObject body = new JSONObject();
            body.putOpt("scroll_id", scrollId);
            body.putOpt("scroll", env.getScrollTime());
            String response = HttpRequest.post(env.getUrl()).header(Header.AUTHORIZATION, env.getApiKey())
                    .header("Content-Type", "application/json")
                    .body(body.toString()).timeout(1000 * 300).execute().body();
            if (response != null) {
                return parse(response);
            }
        }
        return new EsHits();
    }


    public static EsHits parse(String json) {
        EsHits esHits = new EsHits();
        JSONObject jsonObj = JSONUtil.parseObj(json);
//        if (checkResult(jsonObj)) {
//            return esHits;
//        }
        String scrollId = jsonObj.getStr("_scroll_id");
        int histTotal = jsonObj.getJSONObject("hits").getJSONObject("total").getInt("value");
        JSONArray jsonArray = jsonObj.getJSONObject("hits").getJSONArray("hits");
        esHits.setHits(jsonArray);
        esHits.setScrollId(scrollId);
        esHits.setHistTotal(histTotal);
        return esHits;
    }
}
